package com.mall.user.services;/**
 * Created by cskaoyan on 2019/7/30.
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.converter.UserConverterMapper;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.AESUtil;
import com.mall.user.utils.ExceptionProcessorUtils;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * cskaoyan
 */
@Slf4j
@Component
@Service
public class MemberServiceImpl implements IMemberService {

    @Autowired
    MemberMapper memberMapper;

//    @Autowired
//    IUserLoginService userLoginService;

    @Autowired
    MemberConverter memberConverter;

    @Autowired
    JavaMailSender mailSender;

    @Autowired
    UserConverterMapper userConverterMapper;

    /**
     * 根据用户id查询用户会员信息
     *
     * @param request
     * @return
     */
    @Override
    public QueryMemberResponse queryMemberById(QueryMemberRequest request) {

        QueryMemberResponse queryMemberResponse = new QueryMemberResponse();
        try {
            request.requestCheck();
            Member member = memberMapper.selectByPrimaryKey(request.getUserId());
            if (member == null) {
                queryMemberResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
                queryMemberResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
            }
            queryMemberResponse = memberConverter.member2Res(member);
            queryMemberResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            queryMemberResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("MemberServiceImpl.queryMemberById Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(queryMemberResponse, e);
        }
        return queryMemberResponse;
    }


    @Override
    public HeadImageResponse updateHeadImage(HeadImageRequest request) {
        HeadImageResponse response = new HeadImageResponse();
        //TODO
        return response;
    }

    @Override
    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {

        Example example = new Example(Member.class);


        return null;
    }

    /**
     * 验证用户名和email是否被注册过了
     *
     * @param request
     * @return
     */
    @Override
    public UniqueKeyMemberResponse uniqueKeyMember(UniqueKeyMemberRequest request) {

        UniqueKeyMemberResponse response = new UniqueKeyMemberResponse();
        String username = request.getUsername();
        String email = request.getEmail();
        try {
            // 参数非null校验和邮箱格式校验
            request.requestCheck();
            Example example = new Example(Member.class);
            example.createCriteria().orEqualTo("username", username).orEqualTo("email", email);
            List<Member> members = memberMapper.selectByExample(example);
            if (members.size() > 0) {
                // 用户名或者email重复
                response.setCode(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode());
                response.setMsg(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
                return response;
            }
        } catch (Exception e) {
            log.error("MemberServiceImpl.uniqueKeyMember Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);

            return response;
        }

        // 成功
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    /**
     * 插入用户信息
     *
     * @param request
     * @return
     */
    @Override
    public InsertMemberResponse insertMember(InsertMemberRequest request) {

        InsertMemberResponse response = new InsertMemberResponse();

        // 密码加密
        String uuid;
        String password;
        String username;
        String email;

        try {
            request.requestCheck();

            uuid = request.getUuid();
            password = request.getPassword();
            username = request.getUsername();
            email = request.getEmail();
            AESUtil aesUtil = new AESUtil(password);
            String encodePwd = aesUtil.encrypt();

            Member member = new Member();
            member.setEmail(email);
            member.setPassword(encodePwd);
            member.setUsername(username);
            member.setCreated(new Date());
            member.setUpdated(new Date());
            member.setState(1);
            member.setIsVerified("N");

            int affectedRows = memberMapper.insertSelective(member);

            if (affectedRows == 0) {
                // 插入失败，请联系管理员
                log.info("插入失败，请联系管理员");
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }

        } catch (Exception e) {
            log.error("MemberServiceImpl.insertMember Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            return response;
        }


        // 发送邮件  todo 消息队列异步发送邮件
        sendEmail(email, uuid, username);

        log.info("用户注册成功，注册参数request,{}", JSON.toJSONString(request));
        // 成功
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;

    }


    /**
     * 激活用户表信息
     *
     * @param request
     * @return
     */
    @Override
    public VerifyMemberResponse verifyMember(VerifyMemberRequest request) {

        VerifyMemberResponse response = new VerifyMemberResponse();

        String username = request.getUsername();
        String email = request.getEmail();
        String isVerify = request.getIsVerify();

        try {
            request.requestCheck();

            Member member = new Member();
            member.setEmail(email);
            member.setUsername(username);
            member.setUpdated(new Date());
            member.setIsVerified(isVerify);

            Integer affectedRows = memberMapper.updateVerifiedByUsername(member);

            if (affectedRows == 0) {
                // 更新失败
                log.info("用户激活失败");
                response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_UPDATE_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_UPDATE_FAILED.getMessage());
                return response;
            }

        } catch (Exception e) {
            log.error("MemberServiceImpl.uniqueKeyMember Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            // 验证信息不合法
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_UPDATE_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_UPDATE_FAILED.getMessage());
            return response;
        }


        log.info("用户激活成功：request，{}", JSON.toJSONString(request));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;

    }

    @Override
    public UserLoginResponse login(LoginMemberRequest request) {

        UserLoginResponse response = new UserLoginResponse();

        String username = request.getUsername();
        String password = request.getPassword();

        try {
            request.requestCheck();
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username", username);

            // 根据username查用户信息
            List<Member> members = memberMapper.selectByExample(example);
            Member member = members.get(0);

            // 查询用户是否被激活
            if (!"Y".equals(member.getIsVerified())) {
                // 说明没有被激活，无法登录
                response.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
                response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
                return response;
            }

            if (member == null) {
                response.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
                response.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
                return response;
            }
            String encodePwd = member.getPassword();
            AESUtil aesUtil = new AESUtil(encodePwd);
            String decryptPassword = aesUtil.decrypt();

            if (decryptPassword.equals(password)) {

                response = userConverterMapper.converter(member);
                String userInfo = JSON.toJSONString(member);
                log.info("MemberServiceImpl.login: userInfo=" + userInfo);
                String token = JwtTokenUtils.builder().msg(userInfo).build().creatJwtToken();
                log.info("MemberServiceImpl.login: token=" + token);
                response.setToken(token);

                log.info("用户登录成功：request,{}", JSON.toJSONString(request));
                response.setCode(SysRetCodeConstants.SUCCESS.getCode());
                response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
                return response;

            }


        } catch (Exception e) {
            log.error("MemberServiceImpl.login Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
            response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            response.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());

            return response;

        }

        log.info("用户登录失败：request,{}", JSON.toJSONString(request));
        response.setCode(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getCode());
        response.setMsg(SysRetCodeConstants.REQUEST_CHECK_FAILURE.getMessage());

        return response;

    }

    @Override
    public VerifyUserLoginResponse login(String token) {

        VerifyUserLoginResponse response = new VerifyUserLoginResponse();
        // 解密获得username
        Member member = null;
        try {
            // 解析token获得username
            String userInfo = JwtTokenUtils.builder().token(token).build().freeJwt();

            JSONObject object = JSON.parseObject(userInfo);
            String username = object.get("username").toString();

            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username", username);

            // 根据username查用户信息
            List<Member> members = memberMapper.selectByExample(example);
            member = members.get(0);

            if (member == null) {
                response.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
                return response;
            }
        } catch (Exception e) {

            log.info("token已经失效：{}", token);
            response.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
            return response;

        }


        LoginDto loginDto = new LoginDto();

        loginDto.setUsername(member.getUsername());
        loginDto.setUid(member.getId());
        response.setLoginDto(loginDto);

        log.info("用户登录校验成功：request,{}", token);
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());

        return response;

    }


    /**
     * 向注册用户发送邮件
     *
     * @param email
     * @param uuid
     * @param username
     */
    private void sendEmail(String email, String uuid, String username) {

        // 向邮箱中发送连接信息uer/verify,点击连接即激活成功
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("cs-mall 注册用户邮件激活");
        message.setFrom("13813929963@163.com");
        message.setTo(email);
        message.setText("http://localhost:8080/user/verify?uid=" + uuid + "&username=" + username);

        mailSender.send(message);
    }

//    @Override
//    public UpdateMemberResponse updateMember(UpdateMemberRequest request) {
//        UpdateMemberResponse response = new UpdateMemberResponse();
//        try{
//            request.requestCheck();
//            CheckAuthRequest checkAuthRequest = new CheckAuthRequest();
//            checkAuthRequest.setToken(request.getToken());
//            CheckAuthResponse authResponse = userLoginService.validToken(checkAuthRequest);
//            if (!authResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
//                response.setCode(authResponse.getCode());
//                response.setMsg(authResponse.getMsg());
//                return response;
//            }
//            Member member = memberConverter.updateReq2Member(request);
//            int row = memberMapper.updateByPrimaryKeySelective(member);
//            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
//            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
//            log.info("MemberServiceImpl.updateMember effect row :"+row);
//        }catch (Exception e){
//            log.error("MemberServiceImpl.updateMember Occur Exception :"+e);
//            ExceptionProcessorUtils.wrapperHandlerException(response,e);
//        }
//        return response;
//    }
}
